package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.item.dto.SpuDetailDTO;
import com.leyou.item.entity.Spu;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.service.SpecParamService;
import com.leyou.item.service.SpuDetailService;
import com.leyou.item.service.SpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class SpuDetailServiceImpl extends ServiceImpl<SpuDetailMapper, SpuDetail> implements SpuDetailService {


    @Autowired
    private SpuService spuService;
    @Autowired
  private SpecParamService specParamService;


    @Override
    public SpuDetailDTO queryDetailBySpuId(Long spuId) {
//      根据id查询
        SpuDetail detail = getById(spuId);
//        转为DTO
        return new SpuDetailDTO(detail);
    }

    //    根据spuId查询spu的所有规格参数值
    @Override
    public List<SpecParamDTO> queryParamValues(Long id, Boolean searching) {
//        准备规格参数value
//        根据id查询spuDatail
        SpuDetail detail = getById(id);
//        获取其中的规格参数键值对，转为Map
        Map<Long, Object> specValues = JsonUtils.toMap(detail.getSpecification(), Long.class, Object.class);
//        准备规格参数对象
//        根据id查询spu，获取商品分类信息
        SpuDTO spuDTO = spuService.queryGoodsById(id);
        Spu spu = spuDTO.toEntity(Spu.class);
//        根据分类id查询规格参数集合，如果searching不为空，还要加上searching条件
        List<SpecParamDTO> params =  specParamService.queryParams(spu.getCid3(),null,searching);
//        找到param的value，并存储
        for (SpecParamDTO param : params) {
            param.setValue(specValues.get(param.getId()));
        }

        return params;
    }
}
